package tech.kpretty.atomic;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicStampedReference;

public class AtomicRef {
    public static void main(String[] args) {
        AtomicStampedReference<String> ref = new AtomicStampedReference<>("A", 1);

        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(1);// 睡一秒，让t1线程拿到最初的版本号
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ref.compareAndSet("A", "B", ref.getStamp(), ref.getStamp() + 1);
            ref.compareAndSet("B", "A", ref.getStamp(), ref.getStamp() + 1);
        }, "t2").start();
        new Thread(() -> {
            int stamp = ref.getStamp();//拿到最开始的版本号
            try {
                TimeUnit.SECONDS.sleep(3);// 睡3秒，让t2线程的ABA操作执行完
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(ref.compareAndSet("A", "C", stamp, stamp + 1));
        }, "t1").start();
    }
}
